package cn.edu.xaut.mybatisers.mall.ServiceImp;

import cn.edu.xaut.mybatisers.mall.Dao.AdminDao;
import cn.edu.xaut.mybatisers.mall.Entity.*;
import cn.edu.xaut.mybatisers.mall.Exception.ExceptionEntity.LoginException;
import cn.edu.xaut.mybatisers.mall.Service.AdminService;
import cn.edu.xaut.mybatisers.mall.tool.LoginStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@SuppressWarnings("all")
public class AdminServiceImp implements AdminService {
    @Autowired
    AdminDao adminDao;
    @Autowired
    LoginStatus loginStatus;
    @Autowired
    RabbitTemplate rabbitTemplate;

    static DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    @Override
    public Admin login(Admin admin, String verifyCode, HttpServletResponse response, HttpSession session) throws LoginException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, SQLException {
        if(true)
            if (session.getAttribute("dueTime") == null || LocalDateTime.parse(String.valueOf(session.getAttribute("dueTime")), DateTimeFormatter.ofPattern("yyyyMMddHHmm")).isBefore(LocalDateTime.now())){
                throw new LoginException("验证码失效");
            }
        if (!verifyCode.equals(session.getAttribute("verifyCode")) || session.getAttribute("verifyCode") == null){
            throw new LoginException("验证码错误");
        }else {
            session.removeAttribute("verifyCode");
        }
        final ArrayList<Admin> admins = adminDao.login(admin);
        if (admins.size() > 0){
            if (admins.get(0).getPassword().equals(admin.getPassword())){
                String token = loginStatus.generateLoginStatus(admins.get(0).getId());
                response.setHeader("token", token);
                response.setHeader("consumer_id", String.valueOf(admins.get(0).getId()));
                session.setAttribute("admin_id", admins.get(0).getId());
                return admins.get(0);
            }else {
                throw new LoginException("管理员密码错误");
            }
        }else {
            throw new LoginException("管理员账号错误");
        }
    }

    @Override
    public Boolean alterBill(Bill bill) throws SQLException {
        adminDao.alterOrder(bill);
        return true;
    }

    @Override
    public PageInfo<Bill> findBills(Bill bill, String accountMember, int pageNum, int pageSize) throws SQLException {
        if (accountMember != null)
            bill.setConsumer_id(adminDao.findConsumerByAccountMember(accountMember));
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(adminDao.findOrders(bill));
    }

    @Override
    public Boolean addCommodity(Commodity commodity, int admin_id) throws SQLException, IOException {
        if (commodity.getPicture() != null) {
            commodity.setPicture_name(admin_id + LocalDateTime.now().format(ofPattern) + "!" + commodity.getPicture().getOriginalFilename());
            commodity.setPicture(commodity.getPicture());
            File targetFile = new File(System.getProperty("pictureSavePath"));
            if (!targetFile.exists())
                targetFile.mkdir();
            targetFile = new File(System.getProperty("pictureSavePath"), commodity.getPicture_name());
            if (!targetFile.exists())
                targetFile.mkdir();
            commodity.getPicture().transferTo(targetFile);
        }
        if (commodity.getDiscount() == 0)
            commodity.setDiscount(1.00);
        adminDao.addCommodity(commodity);
        System.out.println("新商品id: :" + commodity.getId());
        /**
         *  起一个定时任务将订单超过时未支付就取消
         *  传递参数是订单号
         *  时间是10分钟
         * **/
        if(System.getProperty("delayTask") != null) {
            rabbitTemplate.convertAndSend(
                    "customerExchange",
                    "hotCommodityDelayQueue",
                    commodity.getId(),
                    message -> {
                        message.getMessageProperties().setHeader("x-delay", 600000);
                        return message;
                    }
            );
            System.out.println("发送消息[添加定时任务将新品置为新] " + ">>>>>>>" + LocalDateTime.now());
        }
        return true;
    }

    @Override
    public int deleteCommodity(Commodity commodity) throws SQLException {
        return adminDao.deleteCommodity(commodity);
    }

    @Override
    public Commodity alterCommodity(Commodity commodity) throws SQLException {
        if (adminDao.alterCommodity(commodity) > 0){
            return adminDao.selectCommodity(commodity).get(0);
        }
        return null;
    }

    @Override
    public PageInfo<Commodity> findCommodity(Commodity commodity, int pageNum, int pageSize) throws SQLException, IOException {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(adminDao.selectCommodity(commodity));
    }

    @Override
    public Boolean addCommodityCategory(CommodityCategory commodityCategory) throws SQLException {
        adminDao.addCommodityCategory(commodityCategory);
        return true;
    }

    @Override
    public CommodityCategory alterCommodityCategory(CommodityCategory commodityCategory) throws SQLException {
        adminDao.alterCommodityCategory(commodityCategory);
        return adminDao.getCommodityCategoryById(commodityCategory);
    }

    @Override
    public List<CommodityCategory> findCommodityCategory() throws SQLException {
        return adminDao.findCommodityCategory();
    }

    @Override
    public int deleteCommodityCategory(CommodityCategory commodityCategory) throws SQLException {
        return adminDao.deleteCommodityCategory(commodityCategory);
    }

}









